﻿using KingsSharp.Common;
using KingsSharp.Common.Data;
using KingsSharp.Common.Extensions;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Admin.Services.Service.Sys
{
    public partial class MenuService
    {
        #region 菜单信息
        /// <summary>
        /// 菜单信息集合
        /// </summary>
        public  IQueryable<MenuNode> MenuNodes {

            get { return _menunodeRepository.Entities; }
        }

        /// <summary>
        /// 检测菜单编码是否存在
        /// </summary>
        /// <param name="menucode"></param>
        /// <returns></returns>
        public bool CheckNodeExists(string menucode)
        {
            return _menunodeRepository.Entities.Where(entity => entity.MenuCode == menucode).SingleOrDefault() == null ? false : true;
        }

        /// <summary>
        /// 添加菜单信息
        /// </summary>
        /// <param name="dtos">包含添加信息的菜单信息</param>
        /// <returns></returns>
        public OperationResult AddMenuNode(params MenuNodeDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return _menunodeRepository.Insert(dtos, dto =>
            {
                if (dto.Pid.HasValue)
                {
                    if (_menunodeRepository.ExistsCheck(m => m.Name == dto.Name && m.MenuCatalog != null && m.MenuCatalog.Id == dto.Pid.Value))
                    {
                        throw new Exception("同系统同目录下“{0}”的菜单已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
                else
                {
                    if (_menunodeRepository.ExistsCheck(m => m.Name == dto.Name && m.MenuCatalog != null && m.Type==dto.Type))
                    {
                        throw new Exception("同系统无上级目录“{0}”的菜单已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
            }, (dto, entity) =>
            {
                //if (dto.Pid.HasValue)
                //{
                //    MenuCatalog catalog = _menucatologRepository.GetByKey(dto.Pid.Value);
                //    if (catalog == null)
                //    {
                //        throw new Exception("要加入的上级目录不存在");
                //    }
                //    entity.MenuCatalog = catalog;
                //}
                if (!string.IsNullOrWhiteSpace(dto.ActionPower))
                {
                    List<MenuNodeAction> actionpower = new List<MenuNodeAction>();
                    dto.ActionPower.Split(',').ToList().ForEach(a =>
                    {
                        actionpower.Add(new MenuNodeAction() { 
                            Name=a.Split(':')[1],
                            Code = a.Split(':')[0],
                        });
                    });
                    entity.Actions = actionpower;
                }
                return entity;
            });
        }

        /// <summary>
        /// 更新菜单信息
        /// </summary>
        /// <param name="dtos">包含添加信息的菜单信息</param>
        /// <returns></returns>
        public OperationResult EditMenuNode(params MenuNodeDto[] dtos)
        {
            _menunodeRepository.UnitOfWork.TransactionEnabled = true;
            dtos.CheckNotNull("dtos");
            var result=_menunodeRepository.Update(dtos, dto =>
            {
                if (dto.Pid.HasValue)
                {
                    if (_menunodeRepository.ExistsCheck(m =>m.Id!=dto.Id && m.Name == dto.Name && m.MenuCatalog != null && m.MenuCatalog.Id == dto.Pid.Value))
                    {
                        throw new Exception("同系统同目录下“{0}”的菜单已存在，无法更新。".FormatWith(dto.Name));
                    }
                }
                else
                {
                    if (_menunodeRepository.ExistsCheck(m => m.Id != dto.Id && m.Name == dto.Name && m.MenuCatalog != null && m.Type == dto.Type))
                    {
                        throw new Exception("同系统无上级目录“{0}”的菜单已存在，无法更新。".FormatWith(dto.Name));
                    }
                }
            }, (dto, entity) =>
            {
                //if (dto.Pid.HasValue)
                //{
                //    MenuCatalog catalog = _menucatologRepository.GetByKey(dto.Pid.Value);
                //    if (catalog == null)
                //    {
                //        throw new Exception("要更新的上级目录不存在");
                //    }
                //    entity.MenuCatalog = catalog;
                //}

                _menunodeactionRepository.Delete(a => a.Menu.Id == entity.Id);
                if (!string.IsNullOrWhiteSpace(dto.ActionPower))
                {
                    List<MenuNodeAction> actionpower = new List<MenuNodeAction>();
                    dto.ActionPower.Split(',').ToList().ForEach(a =>
                    {
                        actionpower.Add(new MenuNodeAction()
                        {
                            Name = a.Split(':')[1],
                            Code = a.Split(':')[0],
                        });
                    });
                    entity.Actions = actionpower;
                }
                return entity;
            });
            _menunodeRepository.UnitOfWork.SaveChanges();
            return result;
        }

        /// <summary>
        /// 删除菜单信息
        /// </summary>
        /// <param name="ids">要删除的菜单编号</param>
        /// <returns>业务操作结果</returns>
        public OperationResult DeleteMenuNodes(params Guid[] ids)
        {
            ids.CheckNotNull("ids");
            return _menunodeRepository.Delete(ids);
        }
        #endregion

        #region 菜单的功能权限
        /// <summary>
        /// 菜单功能信息集合
        /// </summary>
        public IQueryable<MenuNodeAction> MenuNodeActions 
        {
            get { return _menunodeactionRepository.Entities; }
        }
        #endregion
    }
}
